﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Shake.Framework.Utility
{
    public class IniUtil
    {
        ////声明读写INI文件的API函数 
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        public string SectionName { get; set; }

        public string IniFilePath { get; set; }

        private IniUtil(string sectionName)
        {
            SectionName = sectionName;
        }

        public static IniUtil GetInstance(string configFileFullname, string sectionName)
        {
            var result = new IniUtil(sectionName) { IniFilePath = configFileFullname };
            return result;
        }


        public void Put(string key, string value)
        {
            WritePrivateProfileString(SectionName, key, value, IniFilePath);
        }

        public string Get(string key)
        {
            var temp = new StringBuilder(255);
            GetPrivateProfileString(SectionName, key, "", temp, 255, IniFilePath);
            return temp.ToString();
        }

        public bool ExistFile()
        {
            return File.Exists(IniFilePath);
        }

        public void ClearAllSection()
        {
            Put(null, null);
        }

        public void ClearSection()
        {
            Put(null, null);
        }
    }
}
